<style lang="less">
    @import '../../../styles/common.less';

    .ivu-page-options-sizer {
        width: 100px;
    }

    .margin-bottom-5 {
        margin-bottom: 5px;
    }

</style>

<template>
    <Row>
        <Row class="margin-top-10">
            <Card>
                <Form ref="SelectformValidate" :model="modalData.Select.formValidate" :label-width="60" inline>
                    <Row>
                        <Form-item label="是否修改" prop="is_update">
                            <Select v-model="modalData.Select.formValidate.is_update" filterable placeholder="请选择">
                                <Option value="null">全部</Option>
                                <Option value="1">已修改</Option>
                                <Option value="0">未修改</Option>
                            </Select>
                        </Form-item>

                        <Form-item label="科室" prop="keshi_id">
                            <Select v-model="modalData.Select.formValidate.keshi_id" filterable placeholder="请选择">
                                <Option value="null">全部</Option>
                                <Option v-for="item in KeshiData" :value="item.id" :key="item.id">{{item.name}}</Option>
                            </Select>
                        </Form-item>

                        <Form-item label="词类" prop="cilei_id">
                            <Select v-model="modalData.Select.formValidate.cilei_id" filterable placeholder="请选择">
                                <Option value="null">全部</Option>
                                <Option v-for="item in CileiData" :value="item.id" :key="item.id">{{item.name}}</Option>
                            </Select>
                        </Form-item>

                        <Form-item label="答案类型" prop="daan_leixing_id">
                            <Select v-model="modalData.Select.formValidate.daan_leixing_id" filterable placeholder="请选择">
                                <Option value="null">全部</Option>
                                <Option v-for="item in DaAnLeiXingData" :value="item.id" :key="item.id">{{item.name}}</Option>
                            </Select>
                        </Form-item>
                    </Row>
                    <Row>
                        <Form-item label="锁定页数" prop="current_page">
                            <Input v-model="table_data.current_page" placeholder="请输入"></Input>
                        </Form-item>

                        <Form-item label="用户名" prop="oper_user_id">
                            <Select v-model="modalData.Select.formValidate.oper_user_id" filterable placeholder="请选择">
                                <Option value="null">全部</Option>
                                <Option v-for="item in UserData" :value="item.id" :key="item.id">{{item.username}}</Option>
                            </Select>
                        </Form-item>

                    </Row>




                </Form>

                <Row type="flex" justify="end" class="code-row-bg">
                    <Button type="primary" @click="SearchData" icon="ios-search">搜索</Button>
                </Row>


            </Card>
        </Row>
        <Row class="margin-top-10">
            <Col span="24">
                <Card>
                    <p slot="title">答案库管理</p>
                    <!--<Row class="margin-bottom-10">-->
                        <!--<Button type="primary" @click="modalAddDisplay">添加</Button>-->
                    <!--</Row>-->

                    <Row class="edittable-table-height-con">
                        <!--<can-edit-table refs="table2" v-model="editInlineData" :columns-list="editInlineColumns"></can-edit-table>-->

                        <Row class-name="margin-bottom-5">
                            <Col span="12">
                                <Button @click="handleSelectAll(true)">设置全选</Button>
                                <Button @click="handleSelectAll(false)">取消全选</Button>
                            </Col>

                            <Col span="6" offset="6" style="text-align: right; padding-right: 20px">
                                <Poptip
                                        confirm
                                        title="您确认批量删除勾选的数据吗?"
                                        @on-ok="batchDelete"
                                >
                                    <Button type="error" icon="trash-b">批量删除</Button>
                                </Poptip>
                            </Col>
                        </Row>
                        <Row>
                            <Table
                                    ref="selection"
                                    border :context="self"
                                    :columns="table_data.header"
                                    :data="table_data.data"
                                    @on-sort-change="tableSort"
                                    size="small"
                            ></Table>
                        </Row>

                    </Row>
                    <Row class="margin-top-10">
                        <Col span="6">
                            <Poptip
                                    confirm
                                    title="您确认批量删除勾选的数据吗?"
                                    @on-ok="batchDelete"
                            >
                                <Button type="error" icon="trash-b">批量删除</Button>
                            </Poptip>
                        </Col>
                        <Col span="18">
                            <Page
                                    :total="table_data.count"
                                    class="float-right"
                                    show-total
                                    show-sizer
                                    show-elevator
                                    @on-change="updateTableCurrentPage"
                                    @on-page-size-change="updateTablePageLength"
                                    :page-size-opts="[10, 25, 50, 100]"
                            ></Page>
                        </Col>

                    </Row>

                </Card>
            </Col>
        </Row>

        <!--<Modal-->
                <!--v-model="modalAdd"-->
                <!--title="添加操作"-->
                <!--width="30%"-->
                <!--:mask-closable="false"-->
        <!--&gt;-->
            <!--<Form ref="AddformValidate" :model="modalData.Add.formValidate" :rules="modalData.Add.ruleValidate" :label-width="100">-->
                <!--<Form-item label="答案类型名称" prop="name" :error="modalData.Add.formItemError.name">-->
                    <!--<Input v-model="modalData.Add.formValidate.name" placeholder="请输入答案类型名称"></Input>-->
                <!--</Form-item>-->
            <!--</Form>-->

            <!--<div slot="footer">-->
                <!--<Button @click="modalAdd=false">取消</Button>-->
                <!--<Button type="primary" :loading="modalData.Add.loading" @click="modalAddFunc">添加</Button>-->
            <!--</div>-->

        <!--</Modal>-->

        <Modal
                v-model="modalUpdate"
                title="修改操作"
                width="40%"
                :mask-closable="false"
        >
            <Row>
                <Col span="10" offset="5" style="color: red">点击要插入的位置按 ctrl --> {zhuanjia}</Col>
            </Row>
            <Row>
                <Col span="10" offset="5" style="color: red">点击要插入的位置按 alt --> {yiyuan}</Col>
            </Row>
            <Form ref="UpdateformValidate" :model="modalData.Update.formValidate" :rules="modalData.Update.ruleValidate" :label-width="100">
                <Form-item label="答案" prop="content" :error="modalData.Update.formItemError.content">
                    <!--<Input ref="xxxxx"  v-model="modalData.Update.formValidate.content" type="textarea" :rows="6" @on-keyup="updateContent" placeholder="请输入答案"></Input>-->
                    <div ref="updateContentDiv" contenteditable="true" @keyup="updateContent" style="border: 1px #dddee1 solid;padding: 2px 10px; line-height: 22px;">
                        {{modalData.Update.formValidate.content}}
                    </div>
                </Form-item>


                <!--KeshiData: [], // 所有科室信息
                CileiData: [], // 所有词类信息
                DaAnLeiXingData: [] // 所有答案类型信息-->

                <Form-item label="科室名称" prop="keshi_id">
                    <Select v-model="modalData.Update.formValidate.keshi_id" :error="modalData.Update.formItemError.keshi_id" placeholder="请选择科室名称" filterable>
                        <Option v-for="item in KeshiData" :value="item.id" :key="item.id">{{item.name}}</Option>
                    </Select>
                </Form-item>

                <Form-item label="词类名称" prop="cilei_id">
                    <Select v-model="modalData.Update.formValidate.cilei_id" :error="modalData.Update.formItemError.cilei_id" placeholder="请选择词类名称" filterable>
                        <Option v-for="item in CileiData" :value="item.id" :key="item.id">{{item.name}}</Option>
                    </Select>
                </Form-item>

                <Form-item label="答案类型名称" prop="daan_leixing_id">
                    <Select v-model="modalData.Update.formValidate.daan_leixing_id" :error="modalData.Update.formItemError.daan_leixing_id" placeholder="请选择答案类型名称" filterable>
                        <Option v-for="item in DaAnLeiXingData" :value="item.id" :key="item.id">{{item.name}}</Option>
                    </Select>
                </Form-item>

            </Form>

            <div slot="footer">
                <Button @click="modalUpdate=false">取消</Button>
                <Button type="primary" :loading="modalData.Update.loading" @click="modalUpdateFunc">修改</Button>
            </div>

        </Modal>

    </Row>
</template>

<script>
    import util from '../../../libs/util';
    import qs from 'qs';
    export default {
        name: 'editable-table',
        data () {
            return {
                test: true,
                modalAdd: false, // 是否显示模态对话框
                modalUpdate: false, // 是否显示模态对话框
                self: this,
                table_data: {
                    header: [
                        {
                            type: 'selection',
                            width: 60,
                            align: 'center'
                        },
                        {
                            title: '编号',
                            type: 'index',
                            width: 60,
                            align: 'center'
                        },
                        {
                            title: '答案',
                            key: 'content',
                            sortable: 'custom'
                        },
                        {
                            title: '词类名称',
                            key: 'cilei__name',
                            width: 105,
                            sortable: 'custom'
                        },
                        {
                            title: '答案类型',
                            key: 'daan_leixing_name',
                            width: 105,
                            sortable: 'custom'
                        },
                        {
                            title: '科室名称',
                            key: 'keshi_name',
                            width: 105,
                            sortable: 'custom'
                        },
                        {
                            title: '操作人',
                            key: 'oper_user__username',
                            width: 75
                        },
                        {
                            title: '创建时间',
                            key: 'create_date',
                            width: 105,
                            sortable: 'custom',
                            render: (h, params) => {
                                let createDate = params.row.create_date ? params.row.create_date.replace('T', ' ') : '';
                                return h('span', createDate);
                            }
                        },
                        {
                            title: '修改时间',
                            width: 105,
                            key: 'update_date',
                            sortable: 'custom',
                            render: (h, params) => {
                                let shenheDate = params.row.update_date ? params.row.update_date.replace('T', ' ') : '';
                                return h('span', shenheDate);
                            }
                        },
                        {
                            title: '操作',
                            key: 'action',
                            width: 165,
                            align: 'center',
                            render: (h, params) => {
                                return [
                                    h('Button', {
                                        props: {
                                            type: 'warning',
                                            size: 'small',
                                            icon: 'edit'
                                        },
                                        on: {
                                            'click': () => {
                                                // 弹出修改模态对话框
                                                this.$refs['UpdateformValidate'].resetFields();
                                                this.modalUpdate = true;
                                                this.modalData.Update.formValidate.content = params.row.content;
                                                this.modalData.Update.formValidate.id = params.row.id;
                                                this.modalData.Update.formValidate.cilei_id = params.row.cilei_id;
                                                this.modalData.Update.formValidate.daan_leixing_id = params.row.daan_leixing_id;
                                                this.modalData.Update.formValidate.keshi_id = params.row.keshi_id;
                                                console.log('update --> params.row', params.row);
                                            }
                                        }
                                    }, '修改'),
                                    h('Poptip', {
                                        props: {
                                            confirm: true,
                                            title: '您确定要删除这条数据吗?',
                                            transfer: true
                                        },
                                        on: {
                                            'on-ok': () => {
                                                let id = params.row.id;
                                                util.ajax.post('wendaku/daanku/delete/' + id).then(res => {
                                                    if (res.data.code === 200) {
                                                        this.modalAdd = false;
                                                        this.$Notice.success({
                                                            title: '删除成功',
                                                            duration: 2
                                                        });
                                                        this.initData();
                                                    } else {
                                                        // 添加失败
                                                        console.log('删除失败 -->', res.data);
                                                    }
                                                });
                                            }
                                        }
                                    }, [
                                        h('Button', {
                                            props: {
                                                type: 'error',
                                                size: 'small',
                                                icon: 'trash-b'
                                            },
                                            style: {
                                                margin: '0 5px'
                                            }
                                        }, '删除')]
                                    )
                                ];
                            }
                        }
                    ],
                    data: [],
                    count: 0,
                    length: 10,
                    current_page: 1,
                    order: '-create_date'
                },
                modalData: {
                    Add: {
                        formValidate: {
                            name: '',
                            pid_id: ''
                        },
                        ruleValidate: {
                            name: [
                                { required: true, message: '词类名称不能为空', trigger: 'blur' }
                            ]
                        },
                        formItemError: {
                            name: '',
                            pid_id: ''
                        },
                        loading: false
                    },
                    Update: {
                        formValidate: {
                            content: '',
                            id: '',
                            cilei_id: '',
                            daan_leixing_id: '',
                            keshi_id: ''
                        },
                        ruleValidate: {
                            content: [
                                { required: true, message: '答案不能为空', trigger: 'blur' }
                            ],
                            cilei_id: [
                                { required: true, type: 'number', message: '词类名称不能为空', trigger: 'blur' }
                            ],
                            daan_leixing_id: [
                                { required: true, type: 'number', message: '答案类型不能为空', trigger: 'blur' }
                            ],
                            keshi_id: [
                                { required: true, type: 'number', message: '科室不能为空', trigger: 'blur' }
                            ]
                        },
                        formItemError: {
                            content: '',
                            id: '',
                            cilei_id: '',
                            daan_leixing_id: '',
                            keshi_id: ''
                        },
                        loading: false
                    },
                    Select: {
                        formValidate: {
                            is_update: 'null',
                            oper_user_id: 'null',
                            cilei_id: 'null',
                            daan_leixing_id: 'null',
                            keshi_id: 'null'
                        }
                    }
                },
                UserData: [], // 所有用户信息
                KeshiData: [], // 所有科室信息
                CileiData: [], // 所有词类信息
                DaAnLeiXingData: [] // 所有答案类型信息
            };
        },
        methods: {
            // 初始化获取表格数据
            initData () {
                let params = {
                    'current_page': this.table_data.current_page,
                    'length': this.table_data.length,
                    'order': this.table_data.order
                };

                for (let key in this.modalData.Select.formValidate) {
                    if (this.modalData.Select.formValidate[key] && this.modalData.Select.formValidate[key] !== 'null') {
                        params[key] = this.modalData.Select.formValidate[key];
                    }
                }
                console.log('params -->', params)
                util.ajax.get('wendaku/daanku', {params: params}).then(res => {
                    if (res.data.code === 200) {
                        console.log('res.data -->', res.data.data);
                        this.table_data.data = res.data.data.ret_data;
                        this.table_data.count = res.data.data.data_count;
                    } else {
                        // 登录失败
                        console.log('获取内容异常');
                    }
                });
            },

            // 点击搜索按钮
            SearchData () {
                this.initData();
            },

            // 弹出增加对话框
            modalAddDisplay () {
                this.modalAdd = true;
                this.$refs['AddformValidate'].resetFields();
            },

            // 修改模态对话框中获取光标所在位置
            getCaretPosition (oField) {
                let iCaretPos = 0;
                let doc = oField.ownerDocument || oField.document;
                let win = doc.defaultView || doc.parentWindow;
                let sel;
                if (typeof win.getSelection !== 'undefined') {
                    sel = win.getSelection();
                    if (sel.rangeCount > 0) {
                        let range = win.getSelection().getRangeAt(0);
                        let preCaretRange = range.cloneRange();
                        preCaretRange.selectNodeContents(oField);
                        preCaretRange.setEnd(range.endContainer, range.endOffset);
                        iCaretPos = preCaretRange.toString().length;
                    }
                } else if ((sel = doc.selection) && sel.type !== 'Control') {
                    let textRange = sel.createRange();
                    let preCaretTextRange = doc.body.createTextRange();
                    preCaretTextRange.moveToElementText(oField);
                    preCaretTextRange.setEndPoint('EndToEnd', textRange);
                    iCaretPos = preCaretTextRange.text.length;
                }
                return (iCaretPos);
            },

            // 修改模态对话框中获取键盘按下事件，输入对应按键插入对应插值
            updateContent (event) {
                console.log(event.keyCode);

                let updateContentDiv = this.$refs.updateContentDiv;
                if (event.keyCode === 17 || event.keyCode === 18) {
                    let index = this.getCaretPosition(updateContentDiv); // 光标所在位置
                    let arr = updateContentDiv.innerHTML.split('');
                    if (event.keyCode === 17) { // ctrl
                        arr.splice(index, 0, '{zhuanjia}');
                    } else if (event.keyCode === 18) { // shift
                        arr.splice(index, 0, '{yiyuan}');
                    }
                    // updateContentDiv.innerHTML = arr.join('');
                    this.modalData.Update.formValidate.content = arr.join('');
                }
            },

            // 全选/全不选
            handleSelectAll (status) {
                this.$refs.selection.selectAll(status);
            },

            // 增加
            modalAddFunc () {
                this.modalData.Add.loading = true;

                // 初始化所有字段错误信息的值
                for (let key in this.modalData.Add.formItemError) {
                    this.modalData.Add.formItemError[key] = '';
                }

                this.$refs['AddformValidate'].validate((valid) => {
                    if (valid) {
                        let params = {
                            'name': this.modalData.Add.formValidate.name
                        };

                        util.ajax.post('wendaku/daanleixing/add/0', qs.stringify(params)).then(res => {
                            if (res.data.code === 200) {
                                this.modalAdd = false;
                                this.$Notice.success({
                                    title: '添加成功',
                                    duration: 2
                                });
                                this.initData();
                            } else {
                                // 添加失败
                                for (let key in res.data.msg) {
                                    this.modalData.Add.formItemError[key] = res.data.msg[key][0].message;
                                }
                            }
                            this.modalData.Add.loading = false;
                        });
                    } else {
                        this.modalData.Add.loading = false;
                    }
                });
            },

            // 修改
            modalUpdateFunc () {
                this.modalData.Update.loading = true;

                console.log('Update.loading -->', this.modalData.Update.loading);
                console.log('this.modalData.Update -->', this.modalData.Update.formValidate);

                // 初始化所有字段错误信息的值
                for (let key in this.modalData.Update.formItemError) {
                    this.modalData.Update.formItemError[key] = '';
                }

                this.$refs['UpdateformValidate'].validate((valid) => {
                    if (valid) {
                        let params = {
                            'content': this.$refs.updateContentDiv.innerHTML,
                            'cilei_id': this.modalData.Update.formValidate.cilei_id,
                            'daan_leixing_id': this.modalData.Update.formValidate.daan_leixing_id,
                            'keshi_id': this.modalData.Update.formValidate.keshi_id
                        };

                        util.ajax.post('wendaku/daanku/update/' + this.modalData.Update.formValidate.id, qs.stringify(params)).then(res => {
                            if (res.data.code === 200) {
                                console.log('修改成功 -->', res.data);
                                this.modalUpdate = false;
                                this.$Notice.success({
                                    title: '修改成功',
                                    duration: 2
                                });
                                this.initData();
                            } else {
                                // 修改失败
                                for (let key in res.data.msg) {
                                    this.modalData.Update.formItemError[key] = res.data.msg[key][0].message;
                                }
                            }

                            this.modalData.Update.loading = false;
                        });
                    } else {
                        // this.$Message.error('表单验证失败!');
                        this.modalData.Update.loading = false;
                    }
                });
            },

            // 批量删除
            batchDelete () {
                let listIds = [];
                let lineObjs = this.$refs.selection.getSelection();
                if (lineObjs.length > 0) {
                    for (let index in lineObjs) {
                        listIds.push(lineObjs[index].id);
                    }

                    let params = {
                        'list_ids': listIds.join(',')
                    };

                    util.ajax.post('wendaku/daanku/batch_delete/0', qs.stringify(params)).then(res => {
                        if (res.data.code === 200) {
                            this.modalAdd = false;
                            this.$Notice.success({
                                title: res.data.msg,
                                duration: 2
                            });
                            this.initData();
                        } else {
                            // 添加失败
                            for (let key in res.data.msg) {
                                this.modalData.Add.formItemError[key] = res.data.msg[key][0].message;
                            }
                        }
                        this.modalData.Add.loading = false;
                    });
                } else {
                    this.$Notice.warning({
                        title: '请勾选需要删除的数据',
                        duration: 2
                    });
                }
            },

            // 当页码被改变是触发
            updateTableCurrentPage (currentPage) {
                this.table_data.current_page = currentPage;
                this.initData();
            },

            // 修改每页显示数量
            updateTablePageLength (length) {
                this.table_data.length = length;
                this.initData();
            },

            // 表格排序触发
            tableSort (e) {
                let key = e.key;
                let order = e.order;

                if (order === 'desc') {
                    this.table_data.order = '-' + key;
                } else {
                    this.table_data.order = key;
                }
                this.initData();
            },

            // 获取所有用户信息
            getUserData () {
                let params = {
                    'current_page': this.table_data.current_page,
                    'length': 0,
                    'order': 'create_date'
                };

                util.ajax.get('wendaku/user', {params: params}).then(res => {
                    if (res.data.code === 200) {
                        this.UserData = res.data.data.ret_data;
                    } else {
                        // 登录失败
                        console.log('获取内容异常');
                    }
                });
            },

            // 获取所有科室信息
            getKeshiData () {
                let params = {
                    'current_page': this.table_data.current_page,
                    'length': 0,
                    'order': 'create_date'
                };

                util.ajax.get('wendaku/keshi', {params: params}).then(res => {
                    if (res.data.code === 200) {
                        this.KeshiData = res.data.data.ret_data;
                    } else {
                        // 登录失败
                        console.log('获取内容异常');
                    }
                });
            },

            // 获取所有词类信息
            getCileiData () {
                let params = {
                    'current_page': this.table_data.current_page,
                    'length': 0,
                    'order': 'create_date'
                };

                util.ajax.get('wendaku/cilei', {params: params}).then(res => {
                    if (res.data.code === 200) {
                        this.CileiData = res.data.data.ret_data;
                    } else {
                        // 登录失败
                        console.log('获取内容异常');
                    }
                });
            },

            // 获取所有答案类型信息
            getDaAnLeiXingData () {
                let params = {
                    'current_page': this.table_data.current_page,
                    'length': 0,
                    'order': 'create_date'
                };

                util.ajax.get('wendaku/daanleixing', {params: params}).then(res => {
                    if (res.data.code === 200) {
                        this.DaAnLeiXingData = res.data.data.ret_data;
                    } else {
                        // 登录失败
                        console.log('获取内容异常');
                    }
                });
            }
        },
        created () {
            this.initData();
            this.getUserData();
            this.getKeshiData();
            this.getCileiData();
            this.getDaAnLeiXingData();
        }
    };
</script>
